package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.dtos.AggBehaviorDTO;
import com.heima.utils.common.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author huan
 * @serial 每天一百行, 致敬未来的自己
 * @Description
 */
@Service
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    AdminFeign adminFeign;
    @Autowired
    ApArticleMapper apArticleMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void computerHotArticle() {
        //1.查询近5天的文章
        //1.1计算5天前的时间
        //1.2使用articleMapper查询文章数据
        String date = LocalDateTime.now().minusDays(5)
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd 00:00:00"));
        List<ApArticle> articleList = apArticleMapper.selectArticleByDate(date);
        //2.计算每一篇文章的热度得分
        List<HotArticleVo> hotArticleVoList = getHotArticleVoList(articleList);
        //3.按照频道 每个频道缓存 热度最高的30条文章
        cacheToRedisByTag(hotArticleVoList);
    }

    @Override
    public void updateApArticle(AggBehaviorDTO mess) {
        //1 查询文章
        ApArticle apArticle = apArticleMapper.selectById(mess.getArticleId());
        if (apArticle == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2 修改文章的行为数据（阅读1、点赞3、评论5、收藏8）
        if (mess.getView() != 0) {
            int view = (int) (apArticle.getViews() == null ? mess.getView() : mess.getView() + apArticle.getViews());
            apArticle.setViews(view);
        }
        if (mess.getLike() != 0) {
            int like = (int) (apArticle.getLikes() == null ? mess.getLike() : mess.getLike() + apArticle.getLikes());
            apArticle.setLikes(like);
        }
        if (mess.getComment() != 0) {
            int comment = (int) (apArticle.getComment() == null ? mess.getComment() : mess.getComment() + apArticle.getComment());
            apArticle.setComment(comment);
        }
        if (mess.getCollect() != 0) {
            int collection = (int) (apArticle.getCollection() == null ? mess.getCollect() : mess.getCollect() + apArticle.getCollection());
            apArticle.setCollection(collection);
        }
        apArticleMapper.updateById(apArticle);
        //3 计算文章分值
        Integer score = computeScore(apArticle);
        // 如果是今天发布的文章，热度*3
        String publishStr = DateUtils.dateToString(apArticle.getPublishTime());
        String nowStr = DateUtils.dateToString(new Date());

        if (publishStr.equals(nowStr)) {
            score = score * 3;
            //当天热点数据 *3
        }
        //4 更新缓存（频道）
        updateArticleCache(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());
        //5 更新推荐列表的缓存
        updateArticleCache(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    private void updateArticleCache(ApArticle apArticle, Integer score, String cacheKey) {
        //1. 从redis中查询对应的文章列表
        String hotArticleJson = redisTemplate.opsForValue().get(cacheKey);
        List<HotArticleVo> hotArticleVoList = JSON.parseArray(hotArticleJson, HotArticleVo.class);
        boolean isHas = false;
        //2. 判断当前文章是否存在热点列表中
        for (HotArticleVo articleVo : hotArticleVoList) {
            if (articleVo.getId().equals(apArticle.getId())) {
                //3. 如果存在,更新文章score热度值
                articleVo.setScore(score);
                isHas = true;
                break;
            }
        }
        //4. 不存在,将当前文章加入热点文章列表
        if (isHas) {
            HotArticleVo articleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticle, articleVo);
            hotArticleVoList.add(articleVo);
        }
        //5. 重新将热点文章列表 按照热度降序排序,截取30条
        hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30).collect(Collectors.toList());
        redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(hotArticleVoList));
    }

    private void cacheToRedisByTag(List<HotArticleVo> hotArticleVoList) {
        //1.远程查询频道列表
        ResponseResult<List<AdChannel>> result = adminFeign.findAll();
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, result.getErrorMessage());
        }
        List<AdChannel> channelList = result.getData();
        //2. 遍历频道列表,从文章列表中筛选每个频道对应的文章,保存 sortAndCache
        channelList.forEach(channel -> {
                    List<HotArticleVo> hotArticleByTag = hotArticleVoList.stream().filter(articleVo ->
                                    articleVo.getChannelId().equals(channel.getId()))
                            .collect(Collectors.toList());
                }
        );
        //3. 推荐频道缓存30条数据  所有文章排序之后的前30条
        sortAndCache(hotArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);

    }

    /**
     * 缓存热点文章
     *
     * @param hotArticleVoList
     * @param cacheKey
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVoList, String cacheKey) {
        //1. 按照热度降序排序 截取前30文章
        hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30).collect(Collectors.toList());
        //2. 缓存到redis中
        redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(hotArticleVoList));
    }

    /**
     * 计算每一篇文章的热度得分
     *
     * @param articleList
     * @return
     */
    private List<HotArticleVo> getHotArticleVoList(List<ApArticle> articleList) {

        return articleList.stream().map(
                apArticle -> {
                    HotArticleVo articleVo = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle, articleVo);
                    Integer score = computeScore(apArticle);
                    articleVo.setScore(score);
                    return articleVo;
                }).collect(Collectors.toList());
    }

    /**
     * 计算文章分数
     *
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        //阅读数量
        Integer views = apArticle.getViews();
        //喜欢数量
        Integer likes = apArticle.getLikes();
        //评论数量
        Integer comment = apArticle.getComment();
        //收藏数量
        Integer collection = apArticle.getCollection();
        if (views != null) {
            score += views * ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }
        if (likes != null) {
            score += likes * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (comment != null) {
            score += comment * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (collection != null) {
            score += collection * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}
